package controller

import (
	"net/http"
	"strconv"
	"text/template"
	"user/services"
)

func GetUsers(w http.ResponseWriter, r *http.Request) {
	// fmt.Fprintf(w, "用户页面")
	tpl := template.Must(template.ParseFiles("./template/user.html"))
	tpl.ExecuteTemplate(w, "user.html", services.GetUsers())
	r.ParseForm()
}

func AddUser(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		tpl := template.Must(template.ParseFiles("./template/create.html"))
		tpl.ExecuteTemplate(w, "create.html", nil)

	} else {
		// tpl := template.Must(template.ParseFiles("./template/create.html"))
		r.ParseForm()
		values := r.PostForm

		services.AddUser(values.Get("name"), values.Get("addr"), values.Get("sex") == "1")

		http.Redirect(w, r, "/", 302)

		// tpl.ExecuteTemplate(w, "create.html", users)
	}

}

func EditUser(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		if id, err := strconv.ParseInt(r.FormValue("id"), 10, 64); err == nil {
			tpl := template.Must(template.ParseFiles("./template/edit.html"))

			tpl.ExecuteTemplate(w, "edit.html", services.GetUser(id))

		}
	} else {
		if id, err := strconv.ParseInt(r.FormValue("id"), 10, 64); err == nil {
			services.EditUser(id, r.FormValue("name"), r.FormValue("addr"), r.FormValue("sex") == "1")
		}
	}
	http.Redirect(w, r, "/", 302)

	//
}

func DelUser(w http.ResponseWriter, r *http.Request) {
	if id, err := strconv.ParseInt(r.FormValue("id"), 10, 64); err == nil {
		services.DelUser(id)

	}
	http.Redirect(w, r, "/", 302)

}
